﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO.Enumeration;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace FunArts.EasyDevOps.Shared.Models.SshClient.CommandResult
{
    public class FileSystemResult : ILinuxCommandResultData<FileSystemResult>
    {
        /// <summary>
        /// 权限字符串 (drwxr-xr-x)
        /// </summary>
        public string Permissions { get; set; }
        /// <summary>
        /// 硬链接数
        /// </summary>
        public int HardLinks { get; set; }
        /// <summary>
        /// 所有者
        /// </summary>
        public string Owner { get; set; }
        /// <summary>
        /// 所属组
        /// </summary>
        public string Group { get; set; }
        /// <summary>
        /// 文件大小(字节)
        /// </summary>
        public long Size { get; set; }
        /// <summary>
        /// 修改日期
        /// </summary>
        public DateTime ModifiedDate { get; set; }
        /// <summary>
        /// 文件/目录名
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 是否为目录
        /// </summary>
        public bool IsDirectory { get; set; }
        /// <summary>
        /// 是否为符号链接
        /// </summary>
        public bool IsSymlink { get; set; }
        /// <summary>
        /// 符号链接目标(如果有)
        /// </summary>
        public string SymlinkTarget { get; set; }

        public List<FileSystemResult> ParseResultDataList(string outData)
        {
            var entries = new List<FileSystemResult>();

            // 标准化行结束符并分割为行
            var lines = outData.Replace("\r\n", "\n").Split('\n')
                               .Where(line => !string.IsNullOrWhiteSpace(line))
                               .ToList();

            // 跳过第一行(total xxxx)
            if (lines.Count > 0 && lines[0].StartsWith("total "))
            {
                lines.RemoveAt(0);
            }

            foreach (var line in lines)
            {
                try
                {
                    var entry = ParseLsLine(line);
                    if (entry != null)
                    {
                        entries.Add(entry);
                    }
                }
                catch (Exception ex)
                {
                    // 记录解析错误但继续处理其他行
                    Console.WriteLine($"解析行失败: {line}. 错误: {ex.Message}");
                }
            }

            return entries;
        }

        private FileSystemResult ParseLsLine(string line)
        {
            // 兼容 CentOS 和 Ubuntu 的不同日期格式:
            // Ubuntu: "Oct 15 10:00" (当年) 或 "Oct 15  2020" (非当年)
            // CentOS: "2020-10-15" (使用 --time-style=long-iso 时)
            var pattern = @"^([bcdlsp-][rwxStT-]{9}\.?)\s+" +  // 权限（含可选的SELinux点）
                    @"(\d+)\s+" +                       // 硬链接数
                    @"(\S+?)\s+" +                      // 所有者（非贪婪匹配）
                    @"(\S+?)\s+" +                      // 所属组（非贪婪匹配）
                    @"(\d+)\s+" +                       // 文件大小
                    @"(\d{4}-\d{2}-\d{2}\s+[\d:]+|\w{3}\s+\d{1,2}\s+(?:\d{4}|[\d:]+)|\d{1,2}\s+\w{3}\s+(?:\d{4}|[\d:]+))\s+" + // 日期
                    @"((.+?)(?:\s+->\s+(.+))?)$";

            var match = Regex.Match(line, pattern);
            if (!match.Success) return null;

            var isSymlink = match.Groups[1].Value[0] == 'l';
            var name = match.Groups[7].Value.Trim();
            string symlinkTarget = null;

            // 处理符号链接
            if (isSymlink && match.Groups[9].Success)
            {
                symlinkTarget = match.Groups[9].Value.Trim();
                // 移除文件名中的链接部分（如果有）
                name = match.Groups[8].Value.Trim();
            }

            var entry = new FileSystemResult
            {
                Permissions = match.Groups[1].Value.Trim(),
                HardLinks = int.Parse(match.Groups[2].Value),
                Owner = match.Groups[3].Value.Trim(),
                Group = match.Groups[4].Value.Trim(),
                Size = long.Parse(match.Groups[5].Value),
                ModifiedDate = ParseUniversalDate(match.Groups[6].Value.Trim()),
                Name = name,
                IsDirectory = match.Groups[1].Value[0] == 'd',
                IsSymlink = isSymlink,
                SymlinkTarget = symlinkTarget
            };

            entry.IsDirectory = entry.Permissions[0] == 'd';
            entry.IsSymlink = entry.Permissions[0] == 'l';

            // 解析符号链接目标
            if (entry.IsSymlink)
            {
                var nameParts = entry.Name.Split(new[] { " -> " }, StringSplitOptions.RemoveEmptyEntries);
                if (nameParts.Length == 2)
                {
                    entry.Name = nameParts[0];
                    entry.SymlinkTarget = nameParts[1];
                }
            }

            return entry;
        }

        private DateTime ParseUniversalDate(string dateStr)
        {
            // 尝试所有可能的格式
            var formats = new[]
            {
        "yyyy-MM-dd",
        "MMM dd HH:mm",
        "dd MMM HH:mm",
        "MMM dd yyyy",
        "dd MMM yyyy",
        "MM月dd日 HH:mm",
        "dd日MM月 HH:mm",
        "M月d日 HH:mm",
        "d日M月 HH:mm",
        "MM月 dd HH:mm",
        "dd MM月 HH:mm",
        "M月 d HH:mm",
        "d M月 HH:mm"
    };

            foreach (var format in formats)
            {
                if (DateTime.TryParseExact(dateStr, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out var date))
                {
                    // 如果日期在未来（可能是缺少年份），调整年份
                    if (date > DateTime.Now && format.Contains("HH:mm"))
                    {
                        return date.AddYears(-1);
                    }
                    return date;
                }
            }

            // 最后尝试系统自动解析
            if (DateTime.TryParse(dateStr, out var fallbackDate))
            {
                return fallbackDate;
            }

            return DateTime.MinValue;
        }

        private int ChineseNumberToInt(string zhNumber)
        {
            if (int.TryParse(zhNumber, out int result))
            {
                return result;
            }

            var zhNumbers = new Dictionary<string, int>
            {
                {"一", 1}, {"二", 2}, {"三", 3}, {"四", 4},
                {"五", 5}, {"六", 6}, {"七", 7}, {"八", 8},
                {"九", 9}, {"十", 10}, {"十一", 11}, {"十二", 12},
            };

            // 移除可能的"月"或"日"后缀
            zhNumber = zhNumber.Replace("月", "").Replace("日", "");

            return zhNumbers.TryGetValue(zhNumber, out int num) ? num : 0;
        }
    }
}
